/***************************************** 
 * Desc: UGUI资源文件配置路径
*****************************************/

using Common.UGUI.Base.Data;
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class UGUIBaseDataWindow : EditorWindow {

    #region 域

    private enum DataType {

        BundlePath = 0,

        CanvasList,
    }

    private struct OneLinePathData{

        public bool IfAdd;

        public bool IfDelete;

        public string UIName;

        public string UIBundlePath;

        public OneLinePathData(string uiName, string bundleName) {
            IfAdd = false;
            IfDelete = false;
            UIName = uiName;
            UIBundlePath = bundleName;
        }
    }

    private struct OneLineCanvasData {

        public bool IfAdd;

        public bool IfDelete;

        public string CanvasName;

        public OneLineCanvasData(string canvasName) {
            IfAdd = false;
            IfDelete = false;
            CanvasName = canvasName;
        }
    }

    public static string UIPrefabAssetsRootPath = "Assets/AssetsPackage/BasicAssets/UI/";
    public static string DataPrefabPath = "Assets/AssetsPackage/BasicAssets/UI/Base/UGUIBaseData.prefab";

    private static string _SearchText = "";
    private static DataType _currentDataType = DataType.BundlePath;
    private static Vector2 _scrollPosition = Vector2.zero;
    private static UGUIBaseDataWindow _window = null;
    private static UGUIBaseData _dataComponent = null;

    private static GUIStyle _TitleLabelText = null;
    private static GUIStyle _SaveButton = null;
    private static GUIStyle _StatusLabelText = null;
    private static GUIStyle _StatusLabelErrorText = null;

    #endregion

    [MenuItem("ThirdParty/GSan/UnityBase/UGUI/ResBundleEditor")]
    public static void OpenUGUIResEditWindow() {

        if (_window == null) {

            _window = EditorWindow.GetWindow<UGUIBaseDataWindow>();
        }

        Vector2 onOpenWH = new Vector2(1000f, 800f);

        // 固定window大小不变
        _window.minSize = onOpenWH;
        _window.maxSize = onOpenWH;

        _window.position = new Rect(new Vector2(500f, 100f), onOpenWH);

        _window.ShowUtility();
    }

    private void OnGUI() {

        InitStyles();

        if(_dataComponent == null) {

            TryLoadDataPrefab();
        }

        GUILayout.BeginVertical();

        ShowDataPrefabPath();
        //GUILayout.Space(UnityEditorCommonConfig.GUILayoutGapSpace);
       // GUILayout.Label(UnityEditorCommonConfig.GUILayoutSegregateLineTextStyle1);
        ShowDataTypeButton();
       // GUILayout.Label(UnityEditorCommonConfig.GUILayoutSegregateLineTextStyle1);
       // GUILayout.Space(UnityEditorCommonConfig.GUILayoutGapSpace);

        if (_dataComponent == null) {

            ShowNoDataPrefabText();

        } else {

            ShowSaveButton();

            ShowResolution();
            
            switch (_currentDataType) {

                case DataType.BundlePath :
                    ShowBundlePathData();
                    break;
                case DataType.CanvasList:
                    ShowBaseCanvasList();
                    break;
            }
        }

        GUILayout.EndVertical();
    }

    #region 自定义UI界面

    #region 通用

    private static void ShowResolution() {

       // GUILayout.Space(UnityEditorCommonConfig.GUILayoutGapSpace);

        GUILayout.BeginVertical();
        GUILayout.Label("Current Logic Resolution:", _TitleLabelText, GUILayout.ExpandWidth(false));
        GUILayout.BeginHorizontal();

        GUILayout.Label("Resolution X:", _StatusLabelText, GUILayout.ExpandWidth(false));
    //    string valueText = UnityEditorHelper.TextFieldText(_dataComponent.ResolutionX.ToString());
        try {

         //   valueText = GUILayout.TextField(valueText, GUILayout.Width(300)) ;
          //  int value = Convert.ToInt32(valueText);
        //    _dataComponent.ResolutionX = value;
        } catch (FormatException e) {
            Debug.LogError("ShowResolution input x error: " + e.Message);
        }

        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();

        GUILayout.Label("Resolution Y:", _StatusLabelText, GUILayout.ExpandWidth(false));
       // valueText = UnityEditorHelper.TextFieldText(_dataComponent.ResolutionY.ToString());
        try {

       //     valueText = GUILayout.TextField(valueText, GUILayout.Width(300));
       //     int value = Convert.ToInt32(valueText);
      //      _dataComponent.ResolutionY = value;
        } catch (FormatException e) {
            Debug.LogError("ShowResolution input y error: " + e.Message);
        }

        GUILayout.EndHorizontal();
        GUILayout.EndVertical();
    }

    private static void ShowSaveButton() {
        if (GUILayout.Button("Save All", _SaveButton, GUILayout.ExpandWidth(false))) {
            EditorUtility.SetDirty(_dataComponent);
            AssetDatabase.SaveAssets();
        }
    }

    private static void ShowDataPrefabPath() {

        GUILayout.BeginHorizontal();

        GUILayout.Label("DataPrefabPath:", _StatusLabelText, GUILayout.ExpandWidth(false));
      //  DataPrefabPath = UnityEditorHelper.TextFieldText(DataPrefabPath);
        DataPrefabPath = GUILayout.TextField(DataPrefabPath, GUILayout.Width(300), GUILayout.ExpandWidth(false));

        GUILayout.EndHorizontal();
    }

    private static void ShowNoDataPrefabText() {
      //  GUILayout.Space(UnityEditorCommonConfig.GUILayoutGapSpace);
        GUILayout.Label("No data prefab to save resource path bundle data now.", _StatusLabelErrorText, GUILayout.ExpandWidth(false));
    }

    private static void ShowDataTypeButton() {

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("UI路径配置", GUILayout.ExpandWidth(false))) {
            _currentDataType = DataType.BundlePath;
        }
        if (GUILayout.Button("基础Canvas配置", GUILayout.ExpandWidth(false))) {
            _currentDataType = DataType.CanvasList;
        }
        GUILayout.EndHorizontal();
    }

    #endregion

    #region Bundle路径信息输入界面

    private const float _TextFieldLen = 300f;

    private static void SearchUIByUIName() {

        GUILayout.BeginHorizontal();
        
        GUILayout.Label("搜索:", _StatusLabelText, GUILayout.ExpandWidth(false));
    //    _SearchText = UnityEditorHelper.TextFieldText(_SearchText);
        _SearchText = GUILayout.TextField(_SearchText, GUILayout.Width(_TextFieldLen));
    //    GUILayout.Space(UnityEditorCommonConfig.GUILayoutGapSpace);

        GUILayout.EndHorizontal();
    }

    private static bool ShowOneLineData(ref OneLinePathData data) {

        GUILayout.BeginHorizontal();

        if (GUILayout.Button("+", GUILayout.ExpandWidth(false))) {
            data.IfAdd = true;
            return true;
        }

        if (GUILayout.Button("-", GUILayout.ExpandWidth(false))) {
            data.IfDelete = true;
            return true;
        }

        GUILayout.Label("UGUIName: ", _StatusLabelText, GUILayout.ExpandWidth(false));
       // data.UIName = UnityEditorHelper.TextFieldText(data.UIName);
        data.UIName = GUILayout.TextField(data.UIName, GUILayout.Width(_TextFieldLen));

        GUILayout.Label("BundlePath: ", _StatusLabelText, GUILayout.ExpandWidth(false));
     //   data.UIBundlePath = UnityEditorHelper.TextFieldText(data.UIBundlePath);
        data.UIBundlePath = GUILayout.TextField(data.UIBundlePath, GUILayout.Width(_TextFieldLen));

        GUILayout.EndHorizontal();

        return false;
    }

    private static void ShowBundlePathData() {

        GUILayout.BeginVertical();

        GUILayout.Label("UGUI名字对应资源Prefab的路径映射配置:", _TitleLabelText, GUILayout.ExpandWidth(false));

        SearchUIByUIName();

        _scrollPosition = GUILayout.BeginScrollView(_scrollPosition);

        List<string> uiNames = _dataComponent.UGUINames;
        List<string> bundlePathes = _dataComponent.UGUIBundlePathes;

        int delta = uiNames.Count - bundlePathes.Count;

        // 先对齐两个数组
        if(delta > 0) {
            for(int i=0; i < delta; ++i) {
                bundlePathes.Add("");
            }
        }else if(delta < 0) {
            delta = Mathf.Abs(delta);
            for (int i = 0; i < delta; ++i) {
                uiNames.Add("");
            }
        }

        int count = uiNames.Count;

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("+(添加到末尾))", GUILayout.ExpandWidth(false))) {

            uiNames.Insert(count, string.Empty);
            bundlePathes.Insert(count, string.Empty);
        }
        if (count > 0) {
            if (GUILayout.Button("-(删除末尾项)", GUILayout.ExpandWidth(false))) {
                uiNames.RemoveAt(count - 1);
                bundlePathes.RemoveAt(count - 1);
            }
        }
        GUILayout.EndHorizontal();

        count = uiNames.Count;

        if (count > 0) {

            bool isShowData = true;

            for (int i = 0; i < count; ++i) {

                isShowData = true;

                if (!string.IsNullOrEmpty(_SearchText)) {

                    if (!uiNames[i].Contains(_SearchText)) {

                        isShowData = false;
                    }
                }

                if (isShowData) {

                    OneLinePathData data = new OneLinePathData(uiNames[i], bundlePathes[i]);

                    if (ShowOneLineData(ref data)) {

                        if (data.IfAdd) {

                            uiNames.Insert(i, string.Empty);
                            bundlePathes.Insert(i, string.Empty);

                            uiNames[i] = uiNames[i + 1];
                            uiNames[i + 1] = string.Empty;
                            bundlePathes[i] = bundlePathes[i + 1];
                            bundlePathes[i + 1] = string.Empty;

                        } else if (data.IfDelete) {

                            uiNames.RemoveAt(i);
                            bundlePathes.RemoveAt(i);
                        }

                        break;
                    }

                    uiNames[i] = data.UIName;
                    bundlePathes[i] = data.UIBundlePath;
                }
            }
        } else {

            GUILayout.Label("No any data. You need \'+\' firstly.", _StatusLabelText, GUILayout.ExpandWidth(false));
        }

        GUILayout.EndScrollView();

        GUILayout.EndVertical();
    }

    #endregion

    #region 基础Canvas列表信息

    private static bool ShowOneLineCanvasData(ref OneLineCanvasData data) {

        GUILayout.BeginHorizontal();

        if (GUILayout.Button("+", GUILayout.ExpandWidth(false))) {
            data.IfAdd = true;
            return true;
        }

        if (GUILayout.Button("-", GUILayout.ExpandWidth(false))) {
            data.IfDelete = true;
            return true;
        }

        GUILayout.Label("CanvasName: ", _StatusLabelText, GUILayout.ExpandWidth(false));
      //  data.CanvasName = UnityEditorHelper.TextFieldText(data.CanvasName);
        data.CanvasName = GUILayout.TextField(data.CanvasName, GUILayout.Width(_TextFieldLen));

        GUILayout.EndHorizontal();

        return false;
    }

    private static void ShowBaseCanvasList() {

        GUILayout.BeginVertical();

        GUILayout.Label("UGUIRoot对应基础必须具备的Canvas名列表:", _TitleLabelText, GUILayout.ExpandWidth(false));

        SearchUIByUIName();

        _scrollPosition = GUILayout.BeginScrollView(_scrollPosition);

        List<string> canvasList = _dataComponent.BaseCanvasList;

        int count = canvasList.Count;       

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("+(添加到末尾))", GUILayout.ExpandWidth(false))) {

            canvasList.Insert(count, string.Empty);
        }
        if (count > 0) {
            if (GUILayout.Button("-(删除末尾项)", GUILayout.ExpandWidth(false))) {

                canvasList.RemoveAt(count - 1);
            }
        }
        GUILayout.EndHorizontal();

        if (GUILayout.Button("Save", GUILayout.ExpandWidth(false))) {
            EditorUtility.SetDirty(_dataComponent);
            AssetDatabase.SaveAssets();
        }

        count = canvasList.Count;

        if (count > 0) {

            bool isShowData = true;

            for (int i = 0; i < count; ++i) {

                isShowData = true;

                if (!string.IsNullOrEmpty(_SearchText)) {

                    if (!canvasList[i].Contains(_SearchText)) {

                        isShowData = false;
                    }
                }

                if (isShowData) {

                    OneLineCanvasData data = new OneLineCanvasData(canvasList[i]);

                    if (ShowOneLineCanvasData(ref data)) {

                        if (data.IfAdd) {

                            canvasList.Insert(i, string.Empty);

                            canvasList[i] = canvasList[i + 1];
                            canvasList[i + 1] = string.Empty;

                        } else if (data.IfDelete) {

                            canvasList.RemoveAt(i);
                        }

                        break;
                    }

                    canvasList[i] = data.CanvasName;
                }
            }
        } else {

            GUILayout.Label("No any data. You need \'+\' firstly.", _StatusLabelText, GUILayout.ExpandWidth(false));
        }

        GUILayout.EndScrollView();

        GUILayout.EndVertical();
    }

    #endregion

    #endregion

    #region 加载资源

    private void TryLoadDataPrefab() {

        GameObject dataPrefa = AssetDatabase.LoadAssetAtPath<GameObject>(DataPrefabPath);

        AssetDatabase.Refresh();

        if (dataPrefa != null) {

            _dataComponent = dataPrefa.GetComponent<UGUIBaseData>();

            if(_dataComponent == null) {

                Debug.LogError("UGUIResEditWindow: DataPrefabPath " + DataPrefabPath + " has GameObject without UGUIBaseData component.");
            }
        } else {

            Debug.LogError("UGUIResEditWindow: DataPrefabPath " + DataPrefabPath + " has no target GameObject.");
        }
    }

    #endregion

    #region 样式

    private static void InitStyles() {

        if(_TitleLabelText == null) {
            _TitleLabelText = new GUIStyle(GUI.skin.label);
            _TitleLabelText.normal.textColor = new Color(0.22f, 0.37f, 0.058f);
            _TitleLabelText.fontSize = 15;
            _TitleLabelText.fontStyle = FontStyle.Bold;
        }

        if(_SaveButton == null) {
            Color buttonColor = new Color( 139/255f, 69/255f, 19/255f);
            _SaveButton = new GUIStyle(GUI.skin.button);
            _SaveButton.fontStyle = FontStyle.Bold;
            _SaveButton.normal.textColor = buttonColor;
            _SaveButton.onNormal.textColor = buttonColor;
            _SaveButton.active.textColor = buttonColor;
            _SaveButton.onActive.textColor = buttonColor;
        }

        if(_StatusLabelText == null) {
            _StatusLabelText = new GUIStyle(GUI.skin.label);
            _StatusLabelText.normal.textColor = Color.blue;
            _StatusLabelText.fontStyle = FontStyle.Bold;
        }

        if (_StatusLabelErrorText == null) {
            _StatusLabelErrorText = new GUIStyle(GUI.skin.label);
            _StatusLabelErrorText.normal.textColor = Color.red;
            _StatusLabelErrorText.fontStyle = FontStyle.Bold;
            _StatusLabelErrorText.fontSize = 20;
        }
    }

    #endregion
}
